﻿using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using iTextSharp.text.pdf;
using iTextSharp.text.pdf.parser;
using System.Globalization;

namespace TestPDFParser
{
    class ProgramBackup
    {
        public static String pdfFilePath = "D:\\3PiR\\Projects\\Elite\\EliteBillingChecker\\Data\\FEV2012\\PDF";
        public static String txtFilePath = "D:\\3PiR\\Projects\\Elite\\EliteBillingChecker\\Data\\FEV2012\\TXT";

        static void MainBackup(string[] args)
        {
            List<String> unidadesPDF = Directory.EnumerateDirectories(pdfFilePath).ToList();
            List<String> unidadesTXT = Directory.EnumerateDirectories(txtFilePath).ToList();

            List<String> unidades = new List<string>();
            foreach (String u in unidadesPDF)
                if (unidadesTXT.Contains(txtFilePath + "\\" + Path.GetFileName(u)))
                    unidades.Add(Path.GetFileName(u));

            //if(unidadesPDF.Where(u => !unidadesTXT.Contains(u)).Count() != 0 || unidadesTXT.Where(u => !unidadesPDF.Contains(u)).Count() != 0)
            //    Environment.Exit(0);

            foreach (String unidade in unidades)
            {
                Console.WriteLine("Unidade " + Path.GetFileName(unidade) + ":");
                List<String> pdfFiles = Directory.EnumerateFiles(pdfFilePath + "\\" + unidade).ToList();
                List<String> txtFiles = Directory.EnumerateFiles(txtFilePath + "\\" + unidade).ToList();

                for (int i = 0; i < pdfFiles.Count; i++)
                {
                    bool flag = false;
                    int txtOld = -1;
                    int pdfOld = -1;
                    for (int j = 0; j < txtFiles.Count; j++)
                    {
                        // Lê info nos arquivos
                        String pdfFile = pdfFiles[i];
                        String txtFile = txtFiles[j];
                        String[] pdfInfo = ReadPdfFile(pdfFile);
                        String[] txtInfo = ReadTxtFile(txtFile);

                        // Check if files match
                        String txtTeste = txtInfo[0].Substring(234, 40).Trim();
                        String pdfTeste = RemoveStress(pdfInfo[0].Split('\n')[pdfInfo[0].Split('\n').ToList().IndexOf("Local de Pagamento:") + 1].Trim().Substring(7).Trim().ToUpper());
                        if (txtTeste != pdfTeste)
                            continue;
                        flag = true; // They match!

                        // Sanity Checks
                        //foreach (string pdfUnit in pdfInfo)
                        //    if (pdfUnit.Split('\n').Length != 72)
                        //        Console.WriteLine("Warning: Unit in pdf file does not have 72 lines.");
                        if (pdfInfo.Length != txtInfo.Length)
                            Console.WriteLine("Error: PDF file has " + pdfInfo.Length + " entries while TXT file has " + txtInfo.Length + ".");

                        //List<int> bla = pdfInfo.Select(s => s.Split('\n').Length).ToList();

                        // Run through files
                        int index = 0;
                        while (index < pdfInfo.Length && index < txtInfo.Length)
                        {
                            double txtValor = Double.Parse(txtInfo[index].TrimStart().Substring(127, 12)) / 100;
                            double pdfValor = Double.Parse(pdfInfo[index].Split('\n')[pdfInfo[index].Split('\n').ToList().IndexOf("(=)Valor do Documento") + 1].Trim());
                            String txtNome = txtInfo[index].Substring(234, 40).Trim();
                            String pdfNome = RemoveStress(pdfInfo[index].Split('\n')[pdfInfo[index].Split('\n').ToList().IndexOf("Local de Pagamento:") + 1].Trim().Substring(7).Trim().ToUpper());

                            if (txtNome != (pdfNome.Length > 40 ? pdfNome.Substring(0, 40) : pdfNome)) // unsynchronized
                            {
                                Console.WriteLine("Error: Values does not match ({0}, {1})", txtValor, pdfValor);
                                // Check errors
                                
                            }
                            else
                            {
                                txtOld = -1;
                                pdfOld = -1;
                                if (txtValor != pdfValor) // values doesn't match, when it should
                                {
                                    Console.WriteLine("Error: Names does not match ({0}, {1})", txtNome, pdfNome);
                                }
                            }
                            index++;
                        }
                        break;
                    }
                    if (!flag)
                        Console.WriteLine("Could not be found matching file to file {0}.", Path.GetFileName(pdfFiles[i]));
                }
            }
            Console.WriteLine();
            Console.Write("Press any key to exit...");
            Console.ReadKey();
        }
        public static String RemoveStress(String word)
        {
            word = word.Replace("Á", "A").Replace("À", "A").Replace("Ã", "A").Replace("Â", "A");
            word = word.Replace("É", "E").Replace("È", "E").Replace("Ê", "E");
            word = word.Replace("Í", "I").Replace("Ì", "I").Replace("Î", "I");
            word = word.Replace("Ó", "O").Replace("Ò", "O").Replace("Õ", "O").Replace("Ô", "O");
            word = word.Replace("Ú", "U").Replace("Ù", "U").Replace("Û", "U");
            word = word.Replace("Ç", "C");
            return word;
        }

        public static String[] ReadPdfFile(String fileName)
        {
            PdfReader reader2 = new PdfReader(fileName);
            string strText = string.Empty;

            for (int page = 1; page <= reader2.NumberOfPages; page++)
            {
                ITextExtractionStrategy its = new iTextSharp.text.pdf.parser.SimpleTextExtractionStrategy();
                PdfReader reader = new PdfReader(fileName);
                String s = PdfTextExtractor.GetTextFromPage(reader, page, its);

                s = Encoding.UTF8.GetString(ASCIIEncoding.Convert(Encoding.Default, Encoding.UTF8, Encoding.Default.GetBytes(s)));
                strText = strText + s;
                reader.Close();
            }
            return strText.Split(new string[] {"Cedente:"}, StringSplitOptions.RemoveEmptyEntries);
        }

        public static String[] ReadTxtFile(String fileName)
        {
            List<String> output = new List<string>();
            using (StreamReader reader = new StreamReader(fileName))
            {
                String line;
                reader.ReadLine(); // Cabeçalho
                while((line = reader.ReadLine()) != null)
                    output.Add(line);
            }
            output.RemoveAt(output.Count - 1);
            return output.ToArray();
        }    
    }
}
